package com.example.myapplication;

import android.media.MediaPlayer;
import android.util.Log;

import java.io.IOException;

public class AudioPlayer {
    private MediaPlayer mediaplayer = new MediaPlayer();

    public void play(String path) {
        if (mediaplayer != null && mediaplayer.isPlaying()) {
            return;
        }
        releaseMediaplayer();
        try {
            mediaplayer = new MediaPlayer();
            mediaplayer.setDataSource("file:////data/user/0/com.example.myapplication/files/arkui-x/entry/resources/rawfile/" + path);
            mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
            mediaplayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    return false;
                }
            });
            mediaplayer.prepareAsync();
        } catch (IOException exception) {
            Log.e("HiHelloWorld", "playMusic IOException "+exception.toString());
        }

    }

    private void releaseMediaplayer() {
        if (mediaplayer != null) {
            mediaplayer.release();
            mediaplayer = null;
        }
    }

    public void stop() {
        releaseMediaplayer();
    }

}